import { FC, useState } from 'react';
import { Form, Input } from 'antd';
import { InputTypeEnum, InputTypeMap } from '../../shared';
import { SubWindowType } from '../../interfaces';

export interface FieldItemProps {
  label?: string;
  name: string;
  inputType: InputTypeEnum;
  options: { value: string; label: string }[];
  children?: FieldItemProps[];
  defaultValue?: any;
  changeType?: (value: any) => any;
  initInputType?: (value: any) => any;
  needChangeType?: true;
  values?: SubWindowType;
  [key: string]: any;
}

const FieldItem: FC<FieldItemProps> = (props) => {
  const {
    label,
    name,
    inputType,
    values,
    initInputType,
    options,
    children,
    changeType,
    style,
    valuePropName,
  } = props;

  const [newInputType, setNewInputType] = useState();
  const onChange = (value: any) => {
    if (changeType && (value == 'px' || value == '%')) {
      setNewInputType(changeType(value));
    }
  };

  const FormItem = InputTypeMap[inputType];

  const fieldProps = {
    style: { width: '100%', ...style },
  };
  if (inputType === InputTypeEnum.Select) {
    (fieldProps as any).allowClear = true;
    (fieldProps as any).options = options;
  }

  return !children ? (
    <Form.Item
      name={name}
      label={label}
      // initialValue={defaultValue}
      style={{ display: 'inline-flex', width: '38%', marginRight: '85px', height: 32 }}
      valuePropName={valuePropName}
    >
      <FormItem {...fieldProps} />
    </Form.Item>
  ) : (
    <Form.Item
      label={label}
      style={{ display: 'inline-flex', width: '38%', marginRight: '85px', height: 32 }}
    >
      <Input.Group compact className={'inbiz-config-subwindow'}>
        {children.map((child) => {
          let type = child.inputType;
          if (child.needChangeType) {
            type = !newInputType ? initInputType?.(values) : newInputType;
          }
          const ChildItem = InputTypeMap[type];
          const innderStyle = child.proportion
            ? child.proportion === '67%'
              ? { width: `67%`, paddingRight: '10px' }
              : { width: '33%' }
            : undefined;
          return (
            <Form.Item key={child.name} name={[name, child.name]} style={innderStyle}>
              <ChildItem options={child.options} onChange={onChange} style={{ width: '100%' }} />
            </Form.Item>
          );
        })}
      </Input.Group>
    </Form.Item>
  );
};

export default FieldItem;
